package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 发布小视频
     *
     * @param pojo
     */
    @Override
    public void add(Video pojo) {
        // idWorker.getNextId("video")中参数video不能修改，给推荐系统使用
        pojo.setVid(idWorker.getNextId("video"));
        pojo.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(pojo);
    }

    /**
     * 通过vid查询视频列表
     *
     * @param vids
     * @return
     */
    @Override
    public List<Video> findByVids(List<Long> vids) {
        Query query = new Query(Criteria.where("vid").in(vids));
        return mongoTemplate.find(query, Video.class);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPage(long page, Long pageSize) {
        List<Video> videoList = new ArrayList<>();
        //1. 统计总数
        Query query = new Query();
        long total = mongoTemplate.count(query, Video.class);
        //2. 总数>start
        long start = (page - 1) * pageSize;
        if (total > start) {
            //3. 设置分页参数
            query.skip(start).limit(pageSize.intValue());
            //4. 按时间降序
            query.with(Sort.by(Sort.Order.desc("created")));
            //5. 查询
            videoList = mongoTemplate.find(query, Video.class);
        }
        //6. 构建pageResult返回
        return new PageResult(page, pageSize, total, videoList);
    }
}
